package com.jinlia.show.modules.base.system.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jinlia.show.modules.base.system.entity.File;
import com.jinlia.show.modules.base.system.mapper.FileMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.regex.Matcher;

@Service
public class FileMapperService  extends ServiceImpl<FileMapper, File> {
    @Value("${file.local-uri}")
    public String localUri;
    public File existName(String originalFilename) {
        File one = this.lambdaQuery()
                .eq(File::getFilename, originalFilename)
                .one();
        if (one != null) {
            if (originalFilename.contains("_")) {
                originalFilename = originalFilename.replaceAll("_", Matcher.quoteReplacement(java.io.File.separator));
            }
            one.setUrl(localUri + originalFilename);
        }
        return one;
    }

    public List<File> getFiles(File file) {
        List<File> list = this.lambdaQuery()
                .eq(StringUtils.hasLength(file.getFilename()), File::getFilename, file.getFilename())
                .list();
        if (!CollectionUtils.isEmpty( list)) {
            list.forEach(fileItem -> {
                String originalFilename = fileItem.getFilename();
                if (originalFilename.contains("_")) {
                    originalFilename = originalFilename.replaceAll("_", Matcher.quoteReplacement(java.io.File.separator));
                }
                fileItem.setUrl(localUri + originalFilename);
            });
        }
        return list;
    }
}
